/**
 * Created by Jack on 2017/7/10.
 */
define(['config', 'text!app/module/system/role.html', 'laypage', 'mydialog', 'autocomplete', 'jqGrid', 'common', 'ztree', 'ztreecheck',
		'css!app/assets/lib/ztree/css/demo.css',
		'css!app/assets/lib/ztree/css/zTreeStyle/zTreeStyle.css'
	],
	function(config, viewHTML, laypage, mydialog, autocomplete, jqGrid,
		common, ztree, ztreecheck) {

		var token = (cache.go("token") === 'undefined') ? 'none' : cache
			.go("token");

		var grid_url = "/api/role";

		var model = avalon.define({
			$id: "roles",
			query: {
				name: "",
			},
			rolesInfo: {
				status: ""
			},
			//statusVal : "",
			ars: [{
				key: "无效",
				val: false
			}, {
				key: "有效",
				val: true
			}],
			init: function() {
				model.loadGrid();
				model.addEvent();
			},

			loadGrid: function() {
				function t(val, opt, row) {
					var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb"  title="修改"><a href="javascript:void();" /></span><span class="fa fa-trash-o mrb"  title="删除"></span></div>'
					avalon.log(html_con)
					return html_con;
				};

				var i = Public.setGrid();
				$("#grid").jqGrid({
					//token验证
					loadBeforeSend: function(jqXHR) {
						jqXHR.setRequestHeader(
							"X-AuthToken", token);
					},
					datatype: "JSON",
					mtype: "POST",
					url: grid_url + "/list",
					postData: model.query.$model,
					//高
					height: i.h,
					//设置jqGrid显示为斑马线样式。就是隔行用不同的背景色区分开
					altRows: true,
					//表格左侧将添加一用于显示行数（从1开始）的列
					rownumbers: true,
					//多选
					multiselect: true,
					//只有点击checkbox时该行才被选中，点击其他列，将清除当前行的选中
					multiboxonly: true,
					//起始页
					page: 1,
					//排序列的名称，此参数会被传到后台
					sortname: "id",
					//排序方式：降序
					sortorder: "desc",
					//定义翻页用的导航栏，必须是有效的html元素
					pager: "#page",
					//在grid上显示记录条数
					rowNum: 10,
					//一个下拉选择框，用来改变显示记录数
					rowList: [10, 30, 50],
					//是否要显示总记录数信息
					viewrecords: true,
					//用来说明当初始化列宽度时候的计算类型，:
					//ture，按比例初始化列宽度
					//false,列宽度使用colModel指定的宽度
					shrinkToFit: false,
					//ture:调整列宽度不会改变表格的宽度,shrinkToFit 为false时，此属性会被忽略
					forceFit: false,
					//描述json 数据格式的数组
					jsonReader: {
						root: "data.list",
						//只读属性，定义了返回的记录数
						records: "data.totalRow",
						//总页数
						total: "data.totalPage",
						repeatitems: false,
						//行id
						id: "id"
					},
					colModel: [{
							name: "operation",
							label: "操作",
							formatter: t,
							align: "center",
							width: '100%',
							title: false
						},
						{
							name: "id",
							label: "ID",
							align: "center",
							width: '220%',
							title: false
						},
						{
							name: "name",
							label: "角色名",
							align: "center",
							width: '220%',
							title: false
						},
						{
							name: "status",
							label: "状态",
							align: "center",
							width: '220%',
							title: false,
							formatter: function(value, options, rowData) {
								if(value) {
									return '有效';
								} else {
									return '无效';
								}
							}
						},
						{
							name: "description",
							label: "描述",
							align: "center",
							width: '220%',
							title: false
						},
						{
							name: "manage",
							label: "权限管理",
							align: "center",
							width: '200%',
							title: false,
							formatter: function(val, opt, row) {
								return '<div class="manage" data-id="' + row.id + '"><a class="rightsManage"   href="javascript:void(0)"  ms-click="editRights(el)"><span>权限设置</span></a></div>'
							}
						}
					],
					cmTemplate: {
						sortable: false,
						title: false
					},
					loadError: function() {
						Public.tips({
							type: 2,
							content: "加载数据出现异常！"
						})
					},
					ondblClickRow: function(t) {
						model.view(t);
					},

				});

			},

			//提交
			reloadData: function() {

				$("#grid").jqGrid("setGridParam", {
					url: grid_url + "/list",
					datatype: "json",
					mtype: 'POST',
					postData: model.query.$model
				}).trigger("reloadGrid");
			},
			//重置
			reset: function() {
				model.query = {
					name: ""
				};
				model.reloadData();
			},
			//设置权限
			editRights: function(id) {
				//发送ajax
				$.ajax({
					type: "POST",
					url: "/api/role/getRights?id=" + id,
					beforeSend: function(xhr) {
						xhr.setRequestHeader("X-AuthToken", token);
					},
					success: function(data, status, xhr) {
						//加载权限树
						model.loadZtree(data);
						dialog({
							title: '权限设置',
							content: $("#editRights"),
							okValue: "确定",
							ok: function() {
								var s = model.submitCheckedNodes();
								$.ajax({
									type: "POST",
									url: "/api/role/saveRights?rightsId=" + s + "&roleId=" + id,
									beforeSend: function(xhr) {
										xhr.setRequestHeader("X-AuthToken", token);
									},
									success: function(data, status, xhr) {
										if(data.success) {
											successDialog().showModal();
										} else {
											errorDialog().showModal();
										}
									}
								})
							},
							cancelValue: "取消",
							cancel: function() {}
						}).showModal();
					},
					error: function(responseData, textStatus, errorThrown) {
						alert("Failed: " +
							responseData);
					}

				});

			},
			//加载 权限树
			loadZtree: function(zNodes) {
				var zTreeObj;
				var setting = {
					check: {
						enable: true
					},
					view: {
						showTitle: true,
						showIcon: true,
						showLine: true,
					},
					data: {
						simpleData: {
							enable: true,
						}
					}
				};
				zTreeObj = $.fn.zTree.init($('#treeDemo'), setting, zNodes);

			},
			//取得Ztree选中的结点 id即权限ID
			submitCheckedNodes: function() {
				var nodes = new Array();
				var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo");
				nodes = zTreeObj.getCheckedNodes(true);
				var str = "";
				for(i = 0; i < nodes.length; i++) {
					if(str != "") {
						str += ",";
					}
					str += nodes[i].id;
				}
				return str;
			},
			//添加或更新
			edit: function(rolesInfo) {
				if(rolesInfo === -1) {
					model.rolesInfo = {
						name: "",
						status: "",
						description: ""
					};
					if(model.rolesInfo.status === "") {
						model.rolesInfo.status = "1";
						model.ars = [{
							key: "无效",
							val: false
						}, {
							key: "有效",
							val: true
						}];
					}
					var url = "/api/role/add";

					dialog({
						title: '添加角色信息',
						content: $("#editRoles"),
						okValue: "确定",
						ok: function() {
							model.rolesInfo.status = model.rolesInfo.status;
							// 提交修改
							$.ajax({
								type: "POST",
								url: url,
								data: model.rolesInfo,
								beforeSend: function(xhr) {
									xhr.setRequestHeader("X-AuthToken", token);
								},
								success: function(data, status, xhr) {
									avalon.log(data);
									model.reset();
								},
								error: function(responseData, textStatus, errorThrown) {
									alert("Failed: " +
										responseData);
								}

							});
							//$.post(url, $("#userForm").serialize());
						},
						cancelValue: "取消",
						cancel: function() {}
					}).showModal();

				} else {
					
					model.rolesInfo = rolesInfo;
					if(model.rolesInfo.status == "无效") {
						model.rolesInfo.status = false;
						model.ars = [{
							key: "无效",
							val: false
						}, {
							key: "有效",
							val: true
						}];
					} else {
						model.rolesInfo.status = true;
						model.ars = [{
							key: "无效",
							val: false
						}, {
							key: "有效",
							val: true
						}];
					}
					//model.rolesInfo = rolesInfo;
					//avalon.log(model.rolesInfo);
					var url = "/api/role/update";
					dialog({
						title: '修改角色信息',
						content: $("#editRoles"),
						okValue: "确定",
						ok: function() {
							model.rolesInfo.status = model.rolesInfo.status;
							// 提交修改
							$.ajax({
								type: "POST",
								url: url,
								contentType: 'application/json;charset=UTF-8',
								data: JSON.stringify(model.rolesInfo),
								beforeSend: function(xhr) {
									xhr.setRequestHeader("X-AuthToken", token);
								},
								success: function(data, status, xhr) {
									model.reset();
								},
								error: function(responseData, textStatus, errorThrown) {
									alert("Failed: " + responseData);
								}

							});

						},
						cancelValue: "取消",
						cancel: function() {}
					}).showModal();

				}

			},

			//删除
			del: function(ids) {
				var url = grid_url + "/delete";
				avalon.log(ids);
				dialog({
					title: '删除用户信息',
					content: '确定删除吗',
					okValue: "确定",

					ok: function() {
						// 删除
						$.ajax({
							type: "POST",
							url: url,
							data: {
								"ids": ids
							},
							beforeSend: function(xhr) {
								xhr.setRequestHeader("X-AuthToken", token);
							},
							success: function(data, status, xhr) {
								avalon.log(data);
								model.reset();
							},
							error: function(responseData, textStatus, errorThrown) {
								alert("Failed: " + responseData);
							}

						});
						//$.post(url, $("#userForm").serialize());
					},
					cancelValue: "取消",
					cancel: function() {}
				}).showModal();

			},

			addEvent: function() {
				//提交
				$("#search").click(function(e) {
					//先阻止浏览器默认跳转行为
					e.preventDefault();
					model.reloadData();
				});

				//重置
				$("#resets").click(function(e) {
					e.preventDefault();
					model.reset();
					model.reloadData();
				});

				$(".grid-wrap").on("click", ".rightsManage", function() {
					var i = $(this).parent().data("id");
					model.editRights(i);
				});
				//修改
				$(".grid-wrap").on("click", ".fa-edit", function() {
					var i = $(this).parent().data("id");
					model.edit($("#grid").getRowData(i));
				});

				//删除
				$(".grid-wrap").on("click", ".fa-trash-o",
					function() {
						var i = $(this).parent().data("id");
						avalon.log(i);
						model.del(i);
					});
				//多项删除
				$("#delete").click(
					function(e) {
						e.preventDefault();
						var t = $("#grid").jqGrid(
							"getGridParam", "selarrrow");
						t.length ? model.del(t.join()) : Public
							.tips({
								type: 2,
								content: "请选择要删除的人员！"
							});

					});

			},

		});

		function errorDialog(data) {
			var mydialog = dialog({
				title: "错误",
				content: "操作失败！",
				okValue: "确定",
				ok: function() {}
			});
			return mydialog;
		}

		function successDialog() {
			var mydialog = dialog({
				title: "成功",
				content: "操作成功！",
				okValue: "确定",
				ok: function() {}
			});
			return mydialog;
		}

		// 定义视图模块
		var viewmod = {
			viewtSrc: viewHTML,
			viewInit: function() {
				model.init();
			}, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
			viewDestroy: function() {} // 切换菜单时销毁原来的view
		};
		return viewmod;
	});